package com.soul.bairong;


import com.alibaba.fastjson.JSONObject;
import com.soul.model.RequestDataDTO;
import com.soul.utils.HttpsInvokeUtil;
import com.soul.utils.EncryptUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;


public class BaiRongInvoke {

    public static String UserName = "119";
    public static String ApiCode = "110";

    /**
     * 登陆token标识
     */
    public static final String SIGN_TOKEN_ID = "tokenid";

    private static volatile String tokenId = null;
    private static boolean isRetry = false;

    private static void paramMd5() {
        System.out.println(EncryptUtil.md5("123456"));
    }

    public static void main(String[] args) {
        paramMd5();
        try {
            //获取token
            tokenId = getTokenId();

            //发送实际请求
            JSONObject reqData = new JSONObject();
            reqData.put("meal", "SpecialList_c");
            reqData.put("id", EncryptUtil.md5("12345689012345678"));
            reqData.put("cell", EncryptUtil.md5("110"));
            reqData.put("name", EncryptUtil.md5("soul"));
            String brResult = sendBrCreditData(reqData.toJSONString(), "test");
            System.out.println("brResult=" + brResult);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getTokenId() {
        String loginResStr = login(UserName, UserName,
                "https://sandbox-api.100credit.cn/bankServer2/user/login.action", ApiCode);
        System.out.println("bairong result：" + loginResStr);
        if (StringUtils.isNotBlank(loginResStr)) {
            JSONObject loginJson = JSONObject.parseObject(loginResStr);
            if (loginJson.containsKey(SIGN_TOKEN_ID)) {
                tokenId = loginJson.getString(SIGN_TOKEN_ID);
                System.out.println("bairong result，tokenId为：" + tokenId);
                return tokenId;
            } else {
                System.out.println("bairong result error，无tokenId！结果为：" + loginResStr);
            }
        }
        return null;
    }


    private static String getCheckData(String jsonData, String apiCode, String tokenId) {
        return EncryptUtil.md5(jsonData + EncryptUtil.md5(apiCode + tokenId));
    }

    public static String login(String userName, String pwd, String loginName, String apiCode) {
        String result = null;
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("userName", userName);
            paramMap.put("password", pwd);
            paramMap.put("apiCode", apiCode);
            result = post(loginName, paramMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 响应code
     */
    public static final String RESPONSE_CODE = "code";
    public static final String TOKEN_OVERDUE = "100007";

    public static String sendBrCreditData(String applyData, String creditType) {

        applyData = RequestDataDTO.generate("https://sandbox-api.100credit.cn/bankServer2/data/terData.action",
                tokenId, applyData);

        System.out.println("bairong result:{}" + creditType + applyData);
        String res = "";
        try {
            res = getApiData(applyData, ApiCode);
            if (StringUtils.isNotBlank(res)) {
                JSONObject json = JSONObject.parseObject(res);
                if (json.containsKey(RESPONSE_CODE) && json.getString(RESPONSE_CODE).equals(TOKEN_OVERDUE)) {
                    com.alibaba.fastjson.JSONObject data = com.alibaba.fastjson.JSONObject.parseObject(applyData);
                    data.put(SIGN_TOKEN_ID, refreshTokenId(tokenId));
                    applyData = data.toJSONString();
                    res = getApiData(applyData, ApiCode);
                }
            }
        } catch (Exception e) {
            System.out.println("bairong result err：" + e);
        }
        System.out.println("bairong result{},response:{}" + creditType + res);
        return res;
    }

    private static String refreshTokenId(String oldTokenId) {

        if (oldTokenId.equals(tokenId)) {
            tokenId = getTokenId(oldTokenId);
        }
        return tokenId;

    }

    private static synchronized String getTokenId(String oldTokenId) {

        if (!oldTokenId.equals(tokenId)) {
            return tokenId;
        }

        return getTokenId();
    }

    public static String getApiData(String jsonData, String apicode) {
        JSONObject jsonObject = null;

        try {
            jsonObject = JSONObject.parseObject(jsonData);
            JSONObject reqDataJsonObject;
            if (!jsonObject.containsKey("reqData")) {
                reqDataJsonObject = new JSONObject();
                reqDataJsonObject.put("code", "500");
                reqDataJsonObject.put("message", "输入参数格式错误！");
                return reqDataJsonObject.toString();
            }

            reqDataJsonObject = jsonObject.getJSONObject("reqData");
            String meal = "";
            String id_photo = "";
            if (reqDataJsonObject.containsKey("meal") && !"".equals(reqDataJsonObject.getString("meal"))) {
                meal = jsonObject.getJSONObject("reqData").getString("meal");
            }

            if (reqDataJsonObject.containsKey("id_photo") && !"".equals(reqDataJsonObject.getString("id_photo"))) {
                id_photo = jsonObject.getJSONObject("reqData").getString("id_photo");
            }

            if (meal.equalsIgnoreCase("OCRId") && id_photo.getBytes().length > 204800) {
                JSONObject jsonjsonObject2 = new JSONObject();
                jsonjsonObject2.put("code", "500");
                jsonjsonObject2.put("message", "图片大小超过200kb！");
                return jsonjsonObject2.toString();
            }
        } catch (Exception var8) {
            var8.printStackTrace();
            JSONObject jsonjsonObject2 = new JSONObject();
            jsonjsonObject2.put("code", "500");
            jsonjsonObject2.put("message", "输入参数不是JSON格式！");
            return jsonjsonObject2.toString();
        }

        return getData(jsonObject.toString(), apicode, isRetry ? 1 : 3);
    }

    protected static String getData(String json, String apiCode, int retryTime) {
        String res_str = "";

        try {
            JSONObject jsonObject = JSONObject.parseObject(json);
            String jsonData = jsonObject.getString("reqData");
            String tokenid = jsonObject.getString("tokenid");
            String checkCode = getCheckData(jsonData, apiCode, tokenid);
            String url = jsonObject.getString("apiName");
            Map<String, Object> paramMap = new HashMap();
            paramMap.put("tokenid", tokenid);
            paramMap.put("apiCode", apiCode);
            paramMap.put("jsonData", jsonData);
            paramMap.put("checkCode", checkCode);
            res_str = post(url, paramMap);
        } catch (Exception var12) {
            var12.printStackTrace();
            if (retryTime < 3) {
                try {
                    Thread.sleep(200L);
                } catch (InterruptedException var11) {
                    var11.printStackTrace();
                }

                System.out.println("因连接或读取超时进行重试，次数为：" + retryTime);
                return getData(json, apiCode, retryTime + 1);
            }

            System.out.println("3次重试失败!");
        }

        return res_str;
    }

    public static String post(String url, Map<String, Object> params) throws IOException {
        HttpPost httppost = new HttpPost(url);
        setKeyValueParams(httppost, params);
        CloseableHttpResponse response = null;
        String result = "";

        try {
            response = HttpsInvokeUtil.getInstance("test").getHttpsClient().execute(httppost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httppost.releaseConnection();
            } catch (IOException var11) {
                var11.printStackTrace();
            }

        }
        return result;
    }


    private static void setJsonParams(HttpPost httpPost, Map<String, Object> params) {
        StringEntity entity = new StringEntity(JSONObject.toJSONString(params), "UTF-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
    }

    private static void setKeyValueParams(HttpPost httpPost, Map<String, Object> params) {
        try {
            List<NameValuePair> nameValuePairList = new ArrayList<>();
            Set<String> keySet = params.keySet();
            Iterator<String> keys = keySet.iterator();

            while (keys.hasNext()) {
                String key = keys.next();
                nameValuePairList.add(new BasicNameValuePair(key, params.get(key).toString()));
            }

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
        } catch (UnsupportedEncodingException err) {
            err.printStackTrace();
        }

    }

}
